package com.token.model.dto;

import com.token.service.Function;

import java.util.*;

/**
 * @auther: henriy
 * @Date: 2023/12/29
 */
public class FunctionTest {

    private final Function<String, Integer> function;

    public FunctionTest(Function<String, Integer> function) {
        this.function = function;
    }

    public Integer testStr(String str) {
        return function.apply(str);
    }

    public static void main(String[] args) {
        // 方式1：通过类构造器打印
        FunctionTest functionTest = new FunctionTest(String::length);
        Integer test = functionTest.testStr("test");
        System.out.println(test);

        // 方式2：直接通过函数式接口打印
        Function<String, Integer> function = String::length;
        Integer functionLength = function.apply("wxw");
        System.out.println(functionLength);

        // andThen用法
        Function<String, Integer> lengthFunction = String::length;
        Function<Integer, Integer> doubleFunction = length -> length * 2;
        Integer doubleLength = lengthFunction.andThen(doubleFunction).apply("www.wdbyte.com");
        System.out.println(doubleLength);

        // listToMap
        List<String> list = Arrays.asList("java", "nodejs", "wdbyte.com");
        // 1，lambda,方式
        Function<String, Integer> length1Function = String::length;
        Map<String, Integer> listToMap = listToMap(list, length1Function);
        System.out.println(listToMap);

        // 2，方法引用方式
        Map<String, Integer> listToMap2 = listToMap(list, String::length);
        System.out.println(listToMap2);

        List<String> list1 = Arrays.asList("Java", "Nodejs", "Wdbyte.com");
        // 方法引用方式
        List<String> upperList = map(list1, String::toUpperCase);
        List<String> lowerList = map(list1, String::toLowerCase);
        System.out.println(upperList);
        System.out.println(lowerList);

        // Lambda 方式
        List<String> upperList2 = map(list1, String::toUpperCase);
        List<String> lowerList2 = map(list1, String::toLowerCase);
        System.out.println(upperList2);
        System.out.println(lowerList2);
    }

    public static <T, R> Map<T, R> listToMap(List<T> list, Function<T, R> function) {
        HashMap<T, R> hashMap = new HashMap<>();
        for (T t : list) {
            hashMap.put(t, function.apply(t));
        }

        return hashMap;
    }

    public static <T, R> List<R> map(List<T> list, Function<T, R> function) {
        List<R> resultList = new ArrayList<>(list.size());
        for (T t : list) {
            resultList.add(function.apply(t));
        }

        return resultList;
    }

}
